#import "ReviewCustomCell.h"
#import "SDWebImage/SDWebImageManager.h"
#import "Masonry/Masonry.h"
#define kAvatarSize 40.0f                // 头像大小
#define kHorizontalPadding 15.0f         // 水平间距
#define kVerticalPadding 12.0f           // 垂直间距
#define kStarSize 15.0f                  // 星星大小
#define kStarSpacing 3.0f                // 星星间距
#define kUserNameFontSize 15.0f          // 用户名字体大小
#define kReviewFontSize 14.0f            // 评价内容字体大小
#define kDateFontSize 12.0f              // 日期字体大小
#define kPhotoPadding 5.0f               // 图片间距
#define kMaxPhotosPerRow 3               // 每行最大图片数

@interface ReviewCustomCell ()

@property (nonatomic, strong) NSMutableArray<UIImageView *> *photoViews; // 图片视图数组

@end

@implementation ReviewCustomCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setupUI];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return self;
}

- (void)setupUI {
    self.backgroundColor = [UIColor whiteColor];
    _photoViews = [NSMutableArray array];
    
    
    __tauserNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 20)];
    __tauserNameLabel.font = [UIFont systemFontOfSize:14.0];
    __tauserNameLabel.textColor = [UIColor redColor];
    [self.contentView addSubview:__tauserNameLabel];
    [__tauserNameLabel setText:@"TA的评价(889)"];
    // 创建日期标签
    _goodComment = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - 20, 10, 80, 20)];
    _goodComment.font = [UIFont systemFontOfSize:14.0];
    _goodComment.textColor = kColorHEX(0x999999);
//    _dateLabel.textAlignment = NSTextAlignmentRight;
    [self.contentView addSubview:_goodComment];
    [_goodComment setText:@"好评度99%>"];
    
    
    // 创建头像
    _avatarImageView = [[UIImageView alloc] init];
    _avatarImageView.layer.cornerRadius = kAvatarSize / 2;
    _avatarImageView.layer.masksToBounds = YES;
    _avatarImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.contentView addSubview:_avatarImageView];
    
    // 创建用户名
    _userNameLabel = [[UILabel alloc] init];
    _userNameLabel.font = [UIFont systemFontOfSize:kUserNameFontSize];
    _userNameLabel.textColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
    [self.contentView addSubview:_userNameLabel];
    
    // 创建评分视图
    _ratingView = [[UIView alloc] init];
    [self.contentView addSubview:_ratingView];
    
    // 创建日期标签
    _dateLabel = [[UILabel alloc] init];
    _dateLabel.font = [UIFont systemFontOfSize:kDateFontSize];
    _dateLabel.textColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];
    [self.contentView addSubview:_dateLabel];
    
    // 创建评价内容
    _reviewLabel = [[UILabel alloc] init];
    _reviewLabel.font = [UIFont systemFontOfSize:kReviewFontSize];
    _reviewLabel.textColor = [UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:1.0];
    _reviewLabel.numberOfLines = 0;
    [self.contentView addSubview:_reviewLabel];
    
    
    // 创建评价内容

    // 创建图片容器
    _photoContainerView = [[UIView alloc] init];
    [self.contentView addSubview:_photoContainerView];
    
    
    _allComment = [UIButton buttonWithType:UIButtonTypeCustom];
    _allComment.titleLabel.font = [UIFont systemFontOfSize:kReviewFontSize];
    [_allComment setTitleColor:kColorHEX(0x333333) forState:UIControlStateNormal];
    [_allComment setTitle:@"查看全部评价" forState:UIControlStateNormal];
//    _allComment.backgroundColor = [UIColor redColor];
//    _allComment = [GradientHelper createHorizontalGradientViewWithFrame:CGRectZero
//                                                                                    startColor:[UIColor colorWithRed:0.9 green:0.4 blue:0.2 alpha:1.0]
//                                                                                      endColor:[UIColor colorWithRed:0.9 green:0.7 blue:0.1 alpha:1.0]];
    
    CAGradientLayer *gradientLayer = [GradientHelper createGradientWithFrame:CGRectMake(0, 0, 200, 200)
                                                                           startColor:kColorHEX(0xFFD800)
                                                                             endColor:kColorHEX(0xFFE44E)];
        
        // 将渐变图层添加到按钮的layer
    [_allComment.layer insertSublayer:gradientLayer atIndex:0];
        
        // 添加布局约束，使渐变图层跟随按钮大小变化
    _allComment.layer.masksToBounds = YES;
    _allComment.layer.cornerRadius = 15.0;
    [_allComment addTarget:self action:@selector(goComment) forControlEvents:UIControlEventTouchUpInside];
    
    [self.contentView addSubview:_allComment];
    
    
    
    // 设置约束
    [__tauserNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).offset(kVerticalPadding / 2);
        make.left.equalTo(self.contentView).offset(10);
        make.height.equalTo(@kAvatarSize);
    }];
    

    // 设置约束
    [_goodComment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(__tauserNameLabel);
        make.right.equalTo(self.contentView).offset(-kHorizontalPadding);
    }];
    
    
    
    // 设置约束
    [_avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(__tauserNameLabel.mas_bottom).offset(kVerticalPadding / 2);
        make.left.equalTo(self.contentView).offset(kHorizontalPadding);
        make.width.height.equalTo(@kAvatarSize);
    }];
    
    [_userNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_avatarImageView);
        make.left.equalTo(_avatarImageView.mas_right).offset(kHorizontalPadding / 2);
    }];
    
    [_ratingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_userNameLabel.mas_bottom).offset(kVerticalPadding / 2);
        make.left.equalTo(_userNameLabel);
        make.height.equalTo(@kStarSize);
    }];
    
    [_dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_avatarImageView);
        make.right.equalTo(self.contentView).offset(-kHorizontalPadding);
    }];
    
    [_reviewLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_avatarImageView.mas_bottom).offset(kVerticalPadding);
        make.left.equalTo(_ratingView.mas_left).offset(0);
        make.right.equalTo(self.contentView).offset(-kHorizontalPadding);
    }];
    
    [_photoContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_reviewLabel.mas_bottom).offset(kVerticalPadding);
        make.left.equalTo(_reviewLabel.mas_left).offset(0);
        make.right.equalTo(self.contentView).offset(-kHorizontalPadding - 10);
    }];
    
    [_allComment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_photoContainerView.mas_bottom).offset(kVerticalPadding / 2 - 10);
        make.centerX.equalTo(self.contentView).offset(0);
        make.left.equalTo(self.contentView).offset(100);
        make.right.equalTo(self.contentView).offset(-100);
        make.bottom.equalTo(self.contentView).offset(-kVerticalPadding);
    }];
}
- (void)goComment
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(goCommentAction:)]) {
        [self.delegate goCommentAction:self];
    }
}
- (void)setupWithAvatar:(UIImage *)avatarImage
               userName:(NSString *)userName
                 rating:(NSInteger)rating
             reviewText:(NSString *)reviewText
             dateString:(NSString *)dateString
              photoUrls:(NSArray<NSString *> *)photoUrls
      placeholderImage:(UIImage *)placeholderImage {
    _avatarImageView.image = avatarImage;
    _userNameLabel.text = userName;
    _reviewLabel.text = reviewText;
    _dateLabel.text = dateString;
    
    [self setupRatingViewWithRating:rating];
    [self setupPhotoViewsWithUrls:photoUrls placeholder:placeholderImage];
}

- (void)setupWithAvatarUrl:(NSString *)avatarUrl
                  userName:(NSString *)userName
                    rating:(NSInteger)rating
                reviewText:(NSString *)reviewText
                dateString:(NSString *)dateString
               photoUrls:(NSArray<NSString *> *)photoUrls
        placeholderImage:(UIImage *)placeholderImage {
    _userNameLabel.text = userName;
    _reviewLabel.text = reviewText;
    _dateLabel.text = dateString;
    
//    [_avatarImageView sd_setImageWithURL:[NSURL URLWithString:avatarUrl] placeholderImage:placeholderImage];
    
    
           SDWebImageManager *manager = [SDWebImageManager sharedManager];
          
           [manager loadImageWithURL:[NSURL URLWithString:avatarUrl] options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
               self->_avatarImageView.image = image;
           }];
    
    [self setupRatingViewWithRating:rating];
    [self setupPhotoViewsWithUrls:photoUrls placeholder:placeholderImage];
}

- (void)setupRatingViewWithRating:(NSInteger)rating {
    // 清除现有星星
    for (UIView *subview in _ratingView.subviews) {
        [subview removeFromSuperview];
    }
    
    // 创建星星
    for (int i = 0; i < 5; i++) {
        UIImageView *starView = [[UIImageView alloc] init];
        starView.contentMode = UIViewContentModeScaleAspectFit;
        
        if (i < rating) {
            // 填充星星
            starView.image = [UIImage imageNamed:@"star_filled"] ?: [UIImage systemImageNamed:@"star.fill"];
        } else {
            // 空心星星
            starView.image = [UIImage imageNamed:@"star_empty"] ?: [UIImage systemImageNamed:@"star"];
        }
        
        [_ratingView addSubview:starView];
        
        [starView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(_ratingView);
            make.width.height.equalTo(@kStarSize);
            make.left.equalTo(_ratingView).offset(i * (kStarSize + kStarSpacing));
        }];
    }
    
    // 设置评分视图宽度
    [_ratingView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(5 * kStarSize + 4 * kStarSpacing));
    }];
}

- (void)setupPhotoViewsWithUrls:(NSArray<NSString *> *)photoUrls placeholder:(UIImage *)placeholder {
    // 清除现有图片视图
    for (UIImageView *photoView in _photoViews) {
        [photoView removeFromSuperview];
    }
    [_photoViews removeAllObjects];
    
    if (!photoUrls || photoUrls.count == 0) {
        // 没有图片，隐藏容器
        [_photoContainerView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@0);
        }];
        return;
    }
    
    // 计算图片大小
    NSInteger photoCount = photoUrls.count;
    NSInteger rows = (photoCount + kMaxPhotosPerRow - 1) / kMaxPhotosPerRow;
    NSInteger cols = MIN(photoCount, kMaxPhotosPerRow);
    
    CGFloat containerWidth = CGRectGetWidth(self.contentView.bounds) - 2 * kHorizontalPadding;
    CGFloat photoSize = (containerWidth - (cols - 1) * kPhotoPadding) / cols;
    
    // 创建图片视图
    for (NSInteger i = 0; i < photoCount; i++) {
        NSInteger row = i / kMaxPhotosPerRow;
        NSInteger col = i % kMaxPhotosPerRow;
        
        UIImageView *photoView = [[UIImageView alloc] init];
        photoView.contentMode = UIViewContentModeScaleAspectFill;
        photoView.clipsToBounds = YES;
        photoView.layer.cornerRadius = 4.0;
        [_photoContainerView addSubview:photoView];
        [_photoViews addObject:photoView];
        
        // 设置图片
        NSString *photoUrl = photoUrls[i];
//        [photoView sd_setImageWithURL:[NSURL URLWithString:photoUrl] placeholderImage:placeholder];
 
        SDWebImageManager *manager = [SDWebImageManager sharedManager];
       
        [manager loadImageWithURL:[NSURL URLWithString:photoUrl] options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            photoView.image = image;
        }];
//         设置约束
        [photoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.equalTo(@(photoSize - 15));
            make.left.equalTo(_photoContainerView).offset(col * (photoSize - 10));
            make.top.equalTo(_photoContainerView).offset(row * (photoSize + kPhotoPadding));
        }];
    }
    
    // 设置容器高度
    [_photoContainerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(rows * photoSize + (rows - 1) * kPhotoPadding));
    }];
    
    [_allComment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_photoContainerView.mas_bottom).offset(kVerticalPadding / 2 - 10);
        make.centerX.equalTo(self.contentView).offset(0);
        make.bottom.equalTo(self.contentView).offset(-kVerticalPadding);
    }];
}

+ (CGFloat)calculateHeightForReviewText:(NSString *)reviewText
                              photoCount:(NSInteger)photoCount
                                 width:(CGFloat)width {
    CGFloat totalHeight = 0;
    
    // 头像区域高度
    CGFloat avatarSectionHeight = kAvatarSize + 2 * kVerticalPadding;
    
    // 评价文本高度
    CGFloat reviewHeight = 0;
    if (reviewText && reviewText.length > 0) {
        UILabel *tempLabel = [[UILabel alloc] init];
        tempLabel.font = [UIFont systemFontOfSize:kReviewFontSize];
        tempLabel.numberOfLines = 0;
        tempLabel.text = reviewText;
        
        CGFloat textWidth = width - 2 * kHorizontalPadding;
        CGSize maxSize = CGSizeMake(textWidth, CGFLOAT_MAX);
        reviewHeight = [tempLabel sizeThatFits:maxSize].height;
    }
    
    // 图片区域高度
    CGFloat photoHeight = 0;
    if (photoCount > 0) {
        NSInteger rows = (photoCount + kMaxPhotosPerRow - 1) / kMaxPhotosPerRow;
        NSInteger cols = MIN(photoCount, kMaxPhotosPerRow);
        
        CGFloat containerWidth = width - 2 * kHorizontalPadding;
        CGFloat photoSize = (containerWidth - (cols - 1) * kPhotoPadding) / cols;
        photoHeight = rows * photoSize + (rows - 1) * kPhotoPadding;
    }
    
    // 计算总高度
    totalHeight = avatarSectionHeight + kVerticalPadding + reviewHeight + kVerticalPadding + photoHeight + kVerticalPadding;
    
    return totalHeight + 60;
}

@end
